#include "app.h"

//
// We MUST reply the request, if error occurs, return 0xFFFFFFFF
//
int frame_trx(void* arg)
{
    int  fd = (int)(U64)arg;   // Fix 64bit compile warning
    char rxbuf[64];
    int  rxbyte;
    int  txbyte;
    U32  result;
    S8   response[16]; // "0x12345678": 10 bytes

    while (1)
    {
        //
        // 0. Init buffer
        //

        memset(rxbuf, 0, sizeof(rxbuf));   // Fix Rx history issue
        memset(response, 0, sizeof(response));

        //
        // 1. RX
        //

        rxbyte = tcp_recv(fd, rxbuf, sizeof(rxbuf), 0);
        GOTO_FAILED(rxbyte <= 0);

        //
        // 2. Process Request
        //    It ALWAYS fill the result, if error, fill with 0xFFFFFFFF
        //

        frame_handler(rxbuf, rxbyte, &result);

        //
        // 3. Process Response
        //    the cmd support ONLY wr/rd, wr will read back, so we ALWAYS return a value
        //    error return 0xFFFFFFFF
        //    
        
        snprintf(response, sizeof(response), "0x%x", result);

        //
        // 4. TX
        //
        
        txbyte = tcp_send(fd, response, (U32)strlen(response), 0);
        GOTO_FAILED(txbyte <= 0);
    }

    return RET_OK;

FAILED:
    tcp_close(fd);

    return RET_FAILED;
}
